package com.bx.implatform.util;

/**
 * @description: 邀请码生成规则
 * @author: cbb
 * @date: 2024-09-14 18
 **/

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bx.implatform.entity.User;
import com.bx.implatform.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.Random;

@Component
public class InviteCodeGenerator {
    private static final int CODE_LENGTH = 6;

    @Resource
    private UserMapper userMapper;

    /**
     * 生成邀请码
     * @return
     */
    public String generate() {
        Random random = new Random();
        String recommendationCode;

        do {
            int randomNumber = random.nextInt(900000) + 100000; // 生成100000到999999之间的随机数
            recommendationCode = String.format("%0" + CODE_LENGTH + "d", randomNumber);
        } while (!isUnique(recommendationCode)); // 检查邀请码是否唯一

        return recommendationCode;
    }

    /**
     * 检查推荐码是否唯一
     * @param code
     * @return
     */
    private boolean isUnique(String code) {
        // TODO: 查询数据库中是否存在该推荐码
        boolean exists = userMapper.exists(new LambdaQueryWrapper<User>()
            .eq(User::getInviteCode, code)
            .eq(User::getStatus, 0));
        return !exists;
    }

}
